//
//  TracingViewController.m
//  CarLifes
//
//  Created by yu on 2017/6/29.
//  Copyright © 2017年 jpas. All rights reserved.
//

#import "TracingViewController.h"
#import "TraceModel.h"
#import "MoveAnnotationView.h"
#import "RoutePlanViewController.h"
#import "EquipmentModel.h"
#import "Utility.h"
#import "LocationManager.h"

@interface TracingViewController ()<MAMapViewDelegate>
{
    CLLocationCoordinate2D *_traceCoordinate;
    MAUserLocation *_userLocation;
    NSUInteger _timerCount;
    BOOL _isComplete;
}

@property (nonatomic, strong) UIButton *locationBtn;

@property (nonatomic, strong) UIButton *overviewBtn;

@property (nonatomic, strong) UIButton *navigationBtn;

@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) NSMutableArray *locationsArray;

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, strong) TraceModel *movedAnnotation;

@property (nonatomic, strong) TraceModel *tModel;

@property (nonatomic, strong) MoveAnnotationView *annotationView;

@property (nonatomic, strong) MAPolyline *polyline;

@property (nonatomic, strong) MAPolyline *straightLine;

@property (nonatomic, strong) UILabel *reloadLabel;

@property (nonatomic, strong) UILabel *addressLabel;

@property (nonatomic, assign) BOOL isFirst;

@property (nonatomic, assign) BOOL isPush;

@property (nonatomic, assign) BOOL isOverview;

@end

@implementation TracingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"实时追踪";
    
    _isComplete = NO;
    self.isOverview = NO;
    _timerCount = 10;
    self.isFirst = YES;
    self.isPush = NO;
    
    [self configSubviews];
    
    [self loadRealTrace];
    
    [self initTimer];
    
    [self reloadEqStatus];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    if (!self.isFirst && !self.isPush) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (self.isFirst) {
        self.isFirst = NO;
    }
    
    if (self.isPush) {
        self.isPush = NO;
    }
}

#pragma mark - Action Handle

/* 当前设备位置 */
- (void)locationAction
{
    if (![LocationManager isLocationEnabled]) {// 用户拒绝开启定位权限
        [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请在系统设置中开启定位服务(设置>隐私>定位服务>开启)，定位您当前位置" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil] show];
        return;
    }
    self.movedAnnotation.coordinate = CLLocationCoordinate2DMake([self.tModel.gdLat doubleValue], [self.tModel.gdLng doubleValue]);
    
    [self.mapView setCenterCoordinate:self.movedAnnotation.coordinate];
    
    [self.mapView setZoomLevel:16 animated:YES];
}

/** 全揽 */
- (void)overviewAction
{
    if (![LocationManager isLocationEnabled]) {// 用户拒绝开启定位权限
        [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请在系统设置中开启定位服务(设置>隐私>定位服务>开启)，定位您当前位置" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil] show];
        return;
    }
    if (self.straightLine == nil) return;
    [self.mapView showOverlays:@[self.straightLine] edgePadding:UIEdgeInsetsMake(100, 80, 50, 100) animated:YES];
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}

/** 导航 */
- (void)naviAction
{
    if (![LocationManager isLocationEnabled]) {// 用户拒绝开启定位权限
        [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请在系统设置中开启定位服务(设置>隐私>定位服务>开启)，才可以导航" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去设置", nil] show];
        return;
    }
    if ([self.tModel.status isEqualToString:@"1"])
    {
        [[[UIAlertView alloc]initWithTitle:@"运动中的设备无法导航" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
    }
    else
    {
        self.isPush = YES;
        RoutePlanViewController *navigation = [[RoutePlanViewController alloc] init];
        navigation.destinationPoint = [[CLLocation alloc] initWithLatitude:[self.tModel.gdLat doubleValue] longitude:[self.tModel.gdLng doubleValue]];
        [self.navigationController
         pushViewController:navigation animated:YES];
    }
}

- (void)showStraightLine
{
    [self.mapView removeOverlay:self.straightLine];
    
    _traceCoordinate[0] = self.movedAnnotation.coordinate;
    _traceCoordinate[1] = _userLocation.coordinate;
    
    self.straightLine = [MAPolyline polylineWithCoordinates:_traceCoordinate count:2];
    
    [self.mapView addOverlay:self.straightLine];
    
}

- (void)initTimer
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                  target:self
                                                selector:@selector(timerAction)
                                                userInfo:nil
                                                 repeats:YES];
    self.timer.fireDate = [NSDate distantPast];
}

- (void)loadRealTrace
{
    [self.requestTool loadRealTrackByEqno:self.eqNo show:NO success:^(TraceModel *tModel) {
        
        if (!tModel) return;
        
        self.tModel = tModel;
        
        [self.locationsArray addObject:tModel];
        
        if (!_isComplete) {
            [self addAnnotationToMap];
            _isComplete = YES;
        }
        
        // 画实时轨迹
        [self addPolyline];
        
        if (self.tModel && _userLocation) {
            [self showStraightLine];
        }
        // 逆地理编码请求
        [self searchReGeocodeWithCoordinate:CLLocationCoordinate2DMake([tModel.gdLat doubleValue], [tModel.gdLng doubleValue])];
        
        // 使设备始终锁定在屏幕中心点移动
        self.movedAnnotation.coordinate = CLLocationCoordinate2DMake([self.tModel.gdLat doubleValue], [self.tModel.gdLng doubleValue]);
        [self.mapView setCenterCoordinate:self.movedAnnotation.coordinate];
        
    } failure:^(NSError *error) {
        PPLog(@"load real track error = %@",error);
    }];
}

- (void)searchReGeocodeWithCoordinate:(CLLocationCoordinate2D)coordinate
{
    [ReGeocodeManager searchReGeocodeWithCoordinate:coordinate reGeocodeBlock:^(AMapReGeocode *reGeocode) {
        AMapPOI *poi = reGeocode.pois[0];
        NSString *format = reGeocode.formattedAddress;
        NSString *poiname = poi.name;
        PPLog(@"%@  -- %ld  --  %@",poi.name,poi.distance,poi.direction);
        
        if ([format containsString:poiname]) poiname = @"";
        self.tModel.address = NSStringFormat(@"%@%@ %@ %ldm",format,poiname,[Utility turnDirection:poi.direction],poi.distance);
        self.addressLabel.text = self.tModel.address;
    } reGeocodeFailBlock:^(NSString *errcode) {
        self.addressLabel.text = errcode;
    }];
}

- (void)reloadSecondLabel
{
    self.reloadLabel.text = NSStringFormat(@"%lds后刷新",_timerCount);
}

- (void)timerAction
{
    _timerCount--;
    
    [self performSelectorOnMainThread:@selector(reloadSecondLabel) withObject:nil waitUntilDone:YES];
    
    if (_timerCount == 1) {
        _timerCount = 10;
    }
    
    if (_timerCount == 9) {
        [self reloadEqStatus];
        [self loadRealTrace];
    }
}

// 画出实时轨迹
- (void)addPolyline {
   
    if (self.polyline == nil)
    {
        self.polyline = [MAPolyline polylineWithCoordinates:NULL count:0];
        [self.mapView addOverlay:self.polyline];
    }
    
    NSUInteger count = 0;
    
    CLLocationCoordinate2D *coordinates = [self coordinatesFromLocationArray:self.locationsArray count:&count];
    if (coordinates != NULL)
    {
        // 重新设置折线坐标点
        [self.polyline setPolylineWithCoordinates:coordinates count:count];
        free(coordinates);
    }
}

// 查询设备状态
- (void)reloadEqStatus
{
    [self.requestTool loadEquipmentListByPage:1 size:1 status:@"" actStatus:@"" str:self.eqNo isNeedDeptId:self.isNeedDeptId show:NO success:^(NSArray *equipments, NSArray *equipCounts) {
        EquipmentModel *eModel = equipments.firstObject;
        NSString *cnStatus = [eModel.cnStatus stringByReplacingOccurrencesOfString:@" " withString:@""];
        self.tModel.ownerName = self.ownerName;
        self.tModel.cnStatus = cnStatus;
        self.annotationView.tModel = self.tModel;
    } failure:^(NSError *error) {
        PPLog(@"tracing error = %@",error.description);
    }];
}

#pragma mark - Utility

- (CLLocationCoordinate2D *)coordinatesFromLocationArray:(NSArray *)locations count:(NSUInteger *)count
{
    if (locations.count == 0)
    {
        return NULL;
    }
    
    *count = locations.count;
    
    CLLocationCoordinate2D *coordinates = (CLLocationCoordinate2D *)malloc(sizeof(CLLocationCoordinate2D) * *count);
    
    for (int i = 0; i < locations.count; i++)
    {
        TraceModel *model = locations[i];
        coordinates[i] = CLLocationCoordinate2DMake([model.gdLat doubleValue], [model.gdLng doubleValue]);
    }
    
    return coordinates;
}

#pragma mark - MAMapViewDelegate

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay
{
    if (overlay == self.polyline)
    {
        MAPolylineRenderer *view = [[MAPolylineRenderer alloc] initWithPolyline:(MAPolyline *)overlay];
        view.lineWidth = 5.0;
        view.strokeColor = [UIColor redColor];
        return view;
    }
    else if (overlay == self.straightLine)
    {
        MAPolylineRenderer *view = [[MAPolylineRenderer alloc] initWithPolyline:(MAPolyline *)overlay];
        view.lineWidth = 2.5;
        view.strokeColor = kBaseColor;
        return view;
    }
    
    return nil;
}

- (void)addAnnotationToMap
{
    self.movedAnnotation = [[TraceModel alloc] init];
    self.movedAnnotation.coordinate = CLLocationCoordinate2DMake([self.tModel.gdLat doubleValue], [self.tModel.gdLng doubleValue]);
    
    [self.mapView addAnnotation:self.movedAnnotation];
    [self.mapView setCenterCoordinate:self.movedAnnotation.coordinate];
    [self.mapView setZoomLevel:16 animated:YES];

    _traceCoordinate = (CLLocationCoordinate2D *)malloc(2 * sizeof(CLLocationCoordinate2D));
}

#pragma mark - MAMapViewDelegate

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation
{
    if(!updatingLocation) return;
    if (userLocation.location.horizontalAccuracy < 0) return;
    
    if (self.tModel)
    {
        _userLocation = userLocation;
        [self showStraightLine];
    }
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    
    if([annotation isKindOfClass:[TraceModel class]]) {
        
        static NSString *annotationIdentifier = @"myLcoationIdentifier";
        
        MoveAnnotationView *annotationView = (MoveAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationIdentifier];
        
        if (annotationView == nil) {
            annotationView = [[MoveAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationIdentifier];
            [annotationView setCanShowCallout:NO];
            annotationView.displayType = DisplayTypeTracing;//实时跟踪
            [annotationView setSelected:YES];
            
        }
    
        // 刷新设备信息和标注点的方向
        annotationView.tModel = self.tModel;
        
        self.annotationView = (MoveAnnotationView *)annotationView;
        
        return annotationView;
    }
    return nil;
}


- (void)configSubviews
{
    [self initMapView];
    
    self.mapView.distanceFilter = kCLLocationAccuracyNearestTenMeters;
    self.mapView.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    
    [self setupButton];
    
    [self setupOtherBtn];
    
    [self setupReloadView];
}

- (void)setupReloadView
{
    UIView *containerView = [[UIView alloc] init];
    [self.view addSubview:containerView];
    containerView.backgroundColor = [kBaseColor colorWithAlphaComponent:0.5];
    
    self.reloadLabel = [[UILabel alloc] init];
    [containerView addSubview:self.reloadLabel];
    self.reloadLabel.text = @"10s后刷新";
    self.reloadLabel.font = [UIFont systemFontOfSize:15];
    self.reloadLabel.textColor = [UIColor whiteColor];
    self.reloadLabel.textAlignment = NSTextAlignmentCenter;
    self.reloadLabel.backgroundColor = [UIColor clearColor];
    
    self.addressLabel = [[UILabel alloc] init];
    [containerView addSubview:self.addressLabel];
    self.addressLabel.backgroundColor = [UIColor clearColor];
    self.addressLabel.text = @"正在解析...";
    self.addressLabel.font = [UIFont systemFontOfSize:15];
    self.addressLabel.textColor = [UIColor whiteColor];
    
    self.reloadLabel.sd_layout
    .topSpaceToView(containerView, 5)
    .leftSpaceToView(containerView, 5)
    .widthIs(70)
    .autoHeightRatio(0);
    
    self.addressLabel.sd_layout
    .leftSpaceToView(self.reloadLabel, 2)
    .topSpaceToView(containerView, 5)
    .rightSpaceToView(containerView, 5)
    .autoHeightRatio(0);
    
    containerView.sd_layout
    .leftEqualToView(self.view)
    .rightEqualToView(self.view)
    .topEqualToView(self.view);
    
    [containerView setupAutoHeightWithBottomView:self.addressLabel bottomMargin:5];
}

- (void)setupOtherBtn
{
    self.locationBtn = [[UIButton alloc] init];
    [self.view addSubview:self.locationBtn];
    [self.locationBtn setImage:IMAGE_NAMED(@"car_location") forState:UIControlStateNormal];
    [self.locationBtn addTarget:self action:@selector(locationAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.overviewBtn = [[UIButton alloc] init];
    [self.view addSubview:self.overviewBtn];
    [self.overviewBtn setImage:IMAGE_NAMED(@"whole_view") forState:UIControlStateNormal];
    [self.overviewBtn addTarget:self action:@selector(overviewAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationBtn = [[UIButton alloc] init];
    [self.view addSubview:self.navigationBtn];
    [self.navigationBtn setImage:IMAGE_NAMED(@"trace_car") forState:UIControlStateNormal];
    [self.navigationBtn addTarget:self action:@selector(naviAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.locationBtn.sd_layout
    .leftEqualToView(self.userLocBtn)
    .bottomSpaceToView(self.userLocBtn, 5)
    .widthRatioToView(self.userLocBtn, 1)
    .heightEqualToWidth();
    
    self.overviewBtn.sd_layout
    .leftEqualToView(self.locationBtn)
    .bottomSpaceToView(self.locationBtn, 5)
    .widthRatioToView(self.locationBtn, 1)
    .heightEqualToWidth();
    
    self.navigationBtn.sd_layout
    .rightEqualToView(self.otherBtnContainer)
    .bottomSpaceToView(self.otherBtnContainer, 5)
    .widthRatioToView(self.otherBtnContainer, 1)
    .heightEqualToWidth();
}

- (NSMutableArray *)locationsArray
{
    if (_locationsArray == nil) {
        _locationsArray = [NSMutableArray array];
    }
    return _locationsArray;
}

- (void)dealloc {
    if (_traceCoordinate) {
        free(_traceCoordinate);
        _traceCoordinate = NULL;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
